package example.decodestring;

import java.util.HashSet;
import java.util.Stack;

/**
 * 将 3[a]2[bc] 转换成 aaabcbc，中括号前面的数字表示重复的次数，可能存在嵌套，如：3[a2[c]]  ===> accaccacc
 * @author changbin.chen
 * @date 2025/4/17
 */
public class Solution {

    public static String decodeString(String str) {
        Stack<String> stack = new Stack<>();
        char[] charArray = str.toCharArray();

        HashSet<String> nums = new HashSet<String>() {{
            add("0");
            add("1");
            add("2");
            add("3");
            add("4");
            add("5");
            add("6");
            add("7");
            add("8");
            add("9");
        }};

        for (char temp : charArray) {
            if (temp != ']') {
                stack.push(String.valueOf(temp));
            } else {
                String combine = "";

                // 弹出括号内容
                while (!stack.peek().equals("[")) {
                    combine = stack.pop() + combine;
                }

                stack.pop(); // 弹出左括号
                String count = "";
                while (!stack.isEmpty() && nums.contains(stack.peek())) {
                    count = stack.pop() + count;
                }

                Integer i = Integer.valueOf(count);
                String res = "";
                for (int j = 0; j < i; j++) {
                    res = res + combine;
                }
                stack.push(res);
            }
        }
        String result = "";
        while (!stack.isEmpty()) {
            result = stack.pop() + result;
        }

        return result;
    }

    public static void main(String[] args) {
        System.out.println(decodeString("abc3[cd]xyz"));
    }

}
